//
//  AddressViewController.m
//  HuaLang
//
//  Created by iking on 2017/12/14.
//  Copyright © 2017年 iking. All rights reserved.
//

#import "AddAddressViewController.h"
#import "AddAddressTableViewCell.h"
//#import "AddAddressViewController.h"
#import "AddressPickerView.h"

@interface AddAddressViewController ()<UITableViewDelegate,UITableViewDataSource,AddressPickerViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL isSelect;
@property (nonatomic ,strong) AddressPickerView *pickerView;
@property (nonatomic, strong) UITextField *areaLB;
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *addressTF;
@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *ZipCodeTF;
@property (nonatomic, strong) NSString *province;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *area;

@end

@implementation AddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"添加地址"];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.pickerView];
    if (self.addressModel) {
        if ([self.addressModel.addressDefault intValue] == 1) {
            self.isSelect = YES;
        }
    }
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddAddressTableViewCell *cell = [[AddAddressTableViewCell alloc] init];
    NSArray *array = @[@"收货人：",@"手机号码：",@"所在地区：",@"详细地址：",@"邮政编码："];
    NSArray *array1 = @[@"请输入收货人姓名",@"请输入手机号码",@"请选择地区",@"街道、楼牌号等",@"6位邮政编码"];
    cell.leftLB.text = array[indexPath.row];
    cell.textField.placeholder = array1[indexPath.row];
    if (indexPath.row == 0) {
        self.nameTF = cell.textField;
        if (self.addressModel) {
            self.nameTF.text = self.addressModel.addressName;
        }
    } else if (indexPath.row == 1) {
        self.phoneTF = cell.textField;
        if (self.addressModel) {
            self.phoneTF.text = self.addressModel.addressPhone;
        }
    } else if (indexPath.row == 2) {
        cell.textField.enabled = NO;
        self.areaLB = cell.textField;
        cell.arrow.hidden = NO;
        if (self.addressModel) {
            self.areaLB.text = [NSString stringWithFormat:@"%@ %@ %@",self.addressModel.addressProvince,self.addressModel.addressCity,self.addressModel.addressArea];
            self.province = self.addressModel.addressProvince;
            self.city = self.addressModel.addressCity;
            self.area = self.addressModel.addressArea;
        }
    } else if (indexPath.row == 3) {
        self.addressTF = cell.textField;
        if (self.addressModel) {
            self.addressTF.text = self.addressModel.addressXX;
        }
    } else {
        self.ZipCodeTF = cell.textField;
        if (self.addressModel) {
            self.ZipCodeTF.text = self.addressModel.addressZipcode;
        }
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(85);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(600);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(600))];
    bgV.backgroundColor = UIColorWhite;
    
    UIButton *selectBtn = [UIButton buttonWithTitle:@" 设为默认地址" fontSize:14 titleColor:UIColorWithRGB(50, 50, 50) background:kClearColor cornerRadius:0];
    if (!self.isSelect) {
        [selectBtn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
    } else {
        [selectBtn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
    }
    [selectBtn sizeToFit];
    [bgV addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgV).offset(10);
        make.left.equalTo(bgV).offset(rateWidth(40));
    }];
    [selectBtn addTarget:self action:@selector(actionSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *btn = [UIButton buttonWithTitle:@"保存" fontSize:16 titleColor:UIColorWhite background:navBarColor cornerRadius:6];
//    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    [btn setImage:UIImageNamed(@"addaddressbaocun") forState:(UIControlStateNormal)];
//    [btn sizeToFit];
    [bgV addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgV);
        make.centerX.equalTo(bgV);
        make.size.mas_offset(CGSizeMake(rateWidth(600), rateHeight(100)));
    }];
    [btn addTarget:self action:@selector(actionAddAddress) forControlEvents:(UIControlEventTouchUpInside)];
    
    return bgV;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        // 选择地区
        [self selectArea];
    }
}
#pragma mark - 添加地址
- (void)actionAddAddress
{
    if (_nameTF.text.length != 0 && _areaLB.text.length != 0 && _addressTF.text.length != 0 && _phoneTF.text.length != 0 && _ZipCodeTF.text.length != 0) {
        if (_ZipCodeTF.text.length == 6) {
            NSString *str;
            if (self.isSelect) {
                str = @"1";
            } else {
                str = @"0";
            }
            NSString *addressid;
            if (self.addressModel) {
                addressid = self.addressModel.addresslId;
            } else {
                addressid = @"0";
            }
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=editaddress&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"addressid":addressid,@"addressName":_nameTF.text,@"addressPhone":_phoneTF.text,@"addressProvince":_province,@"addressCity":_city,@"addressArea":_area,@"addressXX":_addressTF.text,@"addressZipcode":_ZipCodeTF.text,@"addressDefault":str} success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if (responseObject) {
                    if ([responseObject[@"status"] intValue] == 0) {
                        [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                    } else if ([responseObject[@"status"] intValue] > 0) {
                        [MBProgressHUD showSuccess:responseObject[@"returnMsg"]];
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            }];
        } else {
            [TFHUD addRemindHUD:self.view message:@"请输入6位数邮政编码"];
            _ZipCodeTF.text = nil;
        }

    } else {
        [TFHUD addRemindHUD:self.view message:@"请把信息填写完整"];
    }
}
- (void)actionSelect:(UIButton *)btn
{
    self.isSelect = !_isSelect;
    if (self.isSelect) {
        [btn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
    } else {
        [btn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
    }
}
- (void)selectArea
{
    WeakSelf
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        //改变它的frame的x,y的值
        weakSelf.pickerView.frame = CGRectMake(0, kScreenHeight-200, kScreenWidth, 200);
        [UIView commitAnimations];
    }];
}
#pragma mark - AddressPickerViewDelegate
- (void)cancelBtnClick
{
    WeakSelf
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        //改变它的frame的x,y的值
        weakSelf.pickerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
        [UIView commitAnimations];
    }];
}
- (void)sureBtnClickReturnProvince:(NSString *)province City:(NSString *)city Area:(NSString *)area
{
    WeakSelf
    self.areaLB.text = [NSString stringWithFormat:@"%@ %@ %@",province,city,area];
    self.province = province;
    self.city = city;
    self.area = area;
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        //改变它的frame的x,y的值
        weakSelf.pickerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
        [UIView commitAnimations];
    }];
}
- (AddressPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[AddressPickerView alloc]initWithFrame:CGRectMake(0, kScreenHeight , kScreenWidth, 200)];
        _pickerView.delegate = self;
    }
    return _pickerView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColorWhite;
        _tableView.separatorStyle = NO;
        _tableView.scrollEnabled = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
